package com.aqiang.net;

import android.text.TextUtils;

import com.aqiang.net.api.Api;
import com.aqiang.net.entity.TokenEntity;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
    private Retrofit retrofit;
    private static RetrofitManager retrofitManager = new RetrofitManager();
    private RetrofitManager(){
        initRetrofit();
    }

    private void initRetrofit() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(httpLoggingInterceptor)
                .addInterceptor(createInterceptor())
                .writeTimeout(6, TimeUnit.SECONDS)
                .readTimeout(6, TimeUnit.SECONDS)
                .connectTimeout(6, TimeUnit.SECONDS)
                .build();
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(Config.SERVER_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
    }

    private Interceptor createInterceptor() {
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response response = chain.proceed(request);
                if(response.code() == 401){
                    String token = requestToken();
                    if(TextUtils.isEmpty(token)){
                        return response;
                    }
                    Request.Builder builder = request.newBuilder().addHeader("Authorization", "bearer " + token);
                    return chain.proceed(builder.build());
                }
                return response;
            }
        };
        return interceptor;
    }

    private String requestToken() {
        Api api = create(Api.class);
        Call<TokenEntity> token = api.getToken("password",Config.AUTHCODE, "");
        try {
            retrofit2.Response<TokenEntity> execute = token.execute();
            return execute.body().getAccess_token();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static RetrofitManager getInstance(){
        return retrofitManager;
    }

    public <T> T create(Class<T> service){
        return retrofit.create(service);
    }


}
